var ns, UIAlbumBrowser, bmLocation, actionnewdialog;
app = new Vue({
    el: '#app',
    data: {
        newform: {
            PlanID:0,
            ProjectID: 0,
            ProjectName: '',
            CategoryID: 0,
            CategoryName:'',
            ServiceContent: '',
            ServiceEndTime: '',
            InChargeUserID: '',
            UserName:'',//整改处理人
            CheckUserID:0,//验收人id
            CheckUserName:'',//验收人姓名
            ComeFrom:1,//1-临时任务，2-考核任务，3-检查任务
            RelatedID:1,//2-考核任务，3-检查任务
            action:'savequalitycontrol'
        },
        ID:0,
        imglist: [],
        imgEditlist: [],
        imgindex: 0,
        select_imglist: [],
        select_imgindex: 0,  
        ProjectList:[],
        CategoryList: [],
        maxuploadcount: CONFIG.maxuploadcount,
        IsRoomOpen:false,//是否打开问题分类
    },
    methods: {
        get_data: function() {
            var that = this;
            var options = {
                action: 'getqualitycontrolparams'
            };
            ns.post(options, function(succeed, data, err) {
                if (succeed) {
                    that.ProjectList = data.list;
                    if (data.list.length > 0) {
                        that.newform.ProjectID = data.list[0].ID;
                        that.newform.ProjectName = data.list[0].Name;
                    }
                    that.getactions(that.newform.ProjectID);
                    //加载下拉列表数据
                    that.initPicker();
                    if(that.ID>0){
                        that.get_editdata();
                    }
                    
                }
            });
        }, 
        do_select_time: function() {
            var that = this;
            api.openPicker({
                type: 'date',
                date: that.newform.ServiceEndTime,
                title: '选择日期'
            }, function(ret, err) {
                if (ret) {
                    var year = ret.year;
                    var month = (ret.month >= 10 ? ret.month : '0' + ret.month);
                    var day = (ret.day >= 10 ? ret.day : '0' + ret.day);
                    that.newform.ServiceEndTime = year + '/' + month + '/' + day;
                }
            });
        },
        do_save: function() {
            var that = this;
            if (that.newform.ProjectID <= 0) {
                api.toast({
                    msg: '请选择项目',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.CategoryID <= 0) {
                api.toast({
                    msg: '请选择问题分类',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.InChargeUserID == '') {
                api.toast({
                    msg: '请选择处理人',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.CheckUserID == '') {
                api.toast({
                    msg: '请选择验收人',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            if (that.newform.ServiceContent == '') {
                api.toast({
                    msg: '请填写问题描述',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            } 
            if (that.newform.ServiceEndTime == '') {
               api.toast({
                   msg: '请填写整改期限',
                   duration: 2000,
                   location: 'bottom'
               });
               return;
            }
            var date = new Date(that.newform.ServiceEndTime.replace(/-/g, "/"));
            if ((new Date()).valueOf() >= date.valueOf()) {
               api.toast({
                   msg: '整改期限不能早于当前时间',
                   duration: 2000,
                   location: 'bottom'
               });
               return;
            }
            if(that.ID>0){
                that.saveEdit();
            }else{
                that.do_save_process();
            }
           
        },
        saveEdit:function(){
            var that = this;
            var filelist = [];
            for (var i = 0; i < that.imglist.length; i++) {
                if (that.imglist[i].isupload) {
                    filelist.push(that.imglist[i].url);
                }
            }
            var options={};
            options.ID=that.ID;
            options.ProjectID=that.newform.ProjectID;
            options.ProjectName=that.newform.ProjectName;
            options.CategoryID=that.newform.CategoryID;
            options.CategoryName=that.newform.CategoryName;
            options.InChargeUserID=that.newform.InChargeUserID;
            options.UserName=that.newform.UserName;
            options.CheckUserID=that.newform.CheckUserID;
            options.CheckUserName=that.newform.CheckUserName;
            options.ServiceContent=that.newform.ServiceContent;
            options.ServiceEndTime=that.newform.ServiceEndTime;
            options.action="editqualitycontrol";
            ns.post(options, function(succeed, data, err) {
                if(succeed){
                    if(data.status){
                        api.toast({
                            msg: '修改成功',
                            duration: 2000,
                            location: 'bottom'
                        });
                        api.sendEvent({
                                name: 'updata_task_con',
                            });
                            api.sendEvent({
                                name: 'reloadservicelist',
                            });
                            setTimeout(function () {
                                api.closeWin();
                            }, 500);

                    }else{
                        api.toast({
                            msg: '修改失败',
                            duration: 2000,
                            location: 'bottom'
                        });
                    }
                    
                }else{
                    api.toast({
                        msg: '修改失败',
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true,
                files: {
                    file: filelist,
                }
            })


        },
        do_save_process: function() {
            var that = this;
            var filelist = [];
            for (var i = 0; i < that.imglist.length; i++) {
                if (that.imglist[i].isupload) {
                    filelist.push(that.imglist[i].url);
                }
            }
            ns.post(that.newform, function(succeed, data, err) {
                if (succeed) {
                    api.toast({
                        msg: '操作成功',
                        duration: 2000,
                        location: 'bottom'
                    });
                    api.sendEvent({
                        name: 'reloadservicelist',
                    });
                    api.sendEvent({
                        name: 'loadservicelist',
                    });
                    api.sendEvent({
                        name: 'saveservicelist',
                    });
                    api.sendEvent({
                        name: 'home_new_updata',
                        extra: {
                            key1: 'value1',
                        }
                    });    
                    setTimeout(function() {
                        api.closeWin();
                    }, 300)
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true,
                files: {
                    file: filelist
                }
            });
        },
        //选择项目
        do_select_project:function(){
            var that=this;

        },
        do_choose_user: function (type) {
            var that = this;
            var title='';
            if(type==1){
                title="选择处理人"
            }
            if(type==2){
                title="选择验收人"
            }
            ns.openWin('quality_chooseperson', title, {
                ProjectID: that.newform.ProjectID,
                type:type
            });
        },
        //上传图片
        choose_picture: function() {
            var that = this;
            ns.confirmPer('camera', function() {
                that.choose_picture_start();
            })
        },
        choose_picture_start: function() {
            var that = this;
            if (that.imglist.length >= that.maxuploadcount) {
                api.toast({
                    msg: '最多支持' + that.maxuploadcount + '张图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            UIAlbumBrowser.imagePicker({
                max: that.maxuploadcount - that.imglist.length,
                styles: {
                    bg: '#000000',
                    mark: {
                        position: 'top_right',
                        size: 20
                    },
                    nav: {
                        bg: '#000000',
                        cancelColor: '#fff',
                        cancelSize: 16,
                        nextStepColor: '#7fff00',
                        nextStepSize: 16
                    },
                    thumbnail: { //（可选项）返回的缩略图配置，**建议本图片不要设置过大** 若已有缩略图，则使用已有的缩略图。若要重新生成缩略图，可先调用清除缓存接口api.clearCache()。
                        w: 100, //（可选项）数字类型；返回的缩略图的宽；默认：原图的宽度
                        h: 100 //（可选项）数字类型；返回的缩略图的宽；默认：原图的高度
                    }
                },
                animation: true,
            }, function(ret) {
                if (ret.eventType == 'nextStep') {
                    if (ret.list && ret.list.length > 0) {
                        that.select_imglist = ret.list;
                        that.select_imgindex = 0;
                        that.UIAlbumBrowser_transPath();
                    }
                    UIAlbumBrowser.closePicker();
                }
                if (ret.originalPath && ret.originalPath.length > 0) {
                    that.imglist.push({
                        ID: 0,
                        index: that.imgindex,
                        url: ret.originalPath,
                        thumbPath: ret.originalPath,
                        isupload: true
                    });
                    that.imgindex++;
                }
            });
        },
        UIAlbumBrowser_transPath: function() {
            var that = this;
            var item = that.select_imglist[that.select_imgindex];
            UIAlbumBrowser.transPath({
                path: item.path
            }, function(ret, err) {
                if (ret) {
                    that.select_imgindex++;
                    if (that.select_imgindex < that.select_imglist.length) {
                        that.UIAlbumBrowser_transPath();
                    } else {
                        that.select_imgindex = 0;
                    }
                    that.imglist.push({
                        ID: 0,
                        index: that.imgindex,
                        url: ret.path,
                        thumbPath: item.thumbPath,
                        isupload: true
                    });
                    that.imgindex++;
                }
            });
        },
        remove_img: function(index,type,id) {
            var that = this;
            if(type==1){
                for (var i = 0; i < that.imglist.length; i++) {
                    var item = that.imglist[i];
                    if (item.index == index) {
                        that.imglist.splice(i, 1);
                    }
                }
            }else{
                for (var i = 0; i < that.imgEditlist.length; i++) {
                    var item = that.imgEditlist[i];
                    if (item.ID == id) {
                        that.imgEditlist.splice(i, 1);
                    }
                }
                that.do_remove_uploadimg(id);
            }
            
        },
        do_remove_uploadimg: function(id) {
            var that = this;
            var options = {
                action: 'doremoveproductimg',
                RelatedID: id,
                Type:1
            }
            ns.post(options, function(succeed, data, err) {
            });
        },
        do_viewimages: function(activeIndex,type) {
            var that = this;
            var imageUrls = [];
            if(type==1){
                for (var i = 0; i < that.imglist.length; i++) {
                    imageUrls.push(that.imglist[i].url);
                }
            }
            if(type==2){
                for (var i = 0; i < that.imgEditlist.length; i++) {
                    imageUrls.push(that.imgEditlist[i].imgurl);
                }
            }
            var imageBrowser = api.require('imageBrowser');
            imageBrowser.openImages({
                showList: false,
                activeIndex: activeIndex,
                imageUrls: imageUrls
            });
        },
        doChooseUser: function (item) {
            var that = this;
            if (item.length>0) {
                that.newform.InChargeUserID = item[0].id;
                that.newform.UserName = item[0].text;
            }        
        },
        initPicker: function () {
            var _this = this;
            (function ($, doc) {
                $.init();
                $.ready(function () {
                         // 选择项目
                        var pickerProject = new $.PopPicker({
                            layer: 1,
                            fileID: 'ID',
                            fileName:'Name',
                        });
                        var projectData = _this.ProjectList || [];
                        pickerProject.setData(projectData);
                        var showProjectPickerButton = doc.getElementById('chooseproject');
                        showProjectPickerButton.addEventListener('click', function (event) {
                            pickerProject.show(function (items) {
                                _this.newform.ProjectID = items[0].value;
                                _this.newform.ProjectName = items[0].text;
                                _this.getactions(_this.newform.ProjectID);
                                
                                //返回 false 可以阻止选择框的关闭
                                //return false;
                            });
                        }, false);
                });
            })(mui, document);
        },
        //打开问题分类
        do_openQuestion:function(id){
            var that = this;
            that.IsRoomOpen=true;
            that.chooseID = id;

        },
        doCloseRoom:function(){
            var that = this;
            that.IsRoomOpen=false;
        },
        
        //选择分类
        doSelectRoom:function(item){
            var that = this;
            var nowDate=new Date();
            that.IsRoomOpen=false;
            that.newform.CategoryID = item.ID;
            that.newform.CategoryName = item.CategoryName;
            that.newform.CheckUserID = item.CheckUserID;
            that.newform.CheckUserName = item.CheckUserName||'--';
            var date='';
            if(item.LimitTime>0){
                date= new Date(nowDate.setDate(nowDate.getDate()+item.LimitTime));
                
            }else{
                date = nowDate;
            }
            that.newform.ServiceEndTime=date.getFullYear()+"-"
                +((date.getMonth()+1)>9?date.getMonth()+1:"0"+(date.getMonth()+1))+"-"
                +(date.getDate()>9?date.getDate():"0"+date.getDate());

            
        },
        getactions:function(id){
            var nowDate=new Date();
            var that=this;
            var list=[];
            that.CategoryList=[];
            var options = {
                ProjectID:id,
                action: 'getqualitycontrolcategory'
            };
            ns.get(options, function (succeed, data, err) {

                if (succeed) {
                    that.CategoryList = data.list;
                    if (data.list.length > 0) {
                        that.newform.CategoryID = data.list[0].ID;
                        that.newform.CategoryName = data.list[0].CategoryName;
                        that.newform.CheckUserID = data.list[0].CheckUserID;
                        that.newform.CheckUserName = data.list[0].CheckUserName||'--';
                        var date='';
                        if(data.list[0].LimitTime>0){
                           date= new Date(nowDate.setDate(nowDate.getDate()+data.list[0].LimitTime));
                           
                        }else{
                            date = nowDate;
                        }
                        that.newform.ServiceEndTime=date.getFullYear()+"-"
                           +((date.getMonth()+1)>9?date.getMonth()+1:"0"+(date.getMonth()+1))+"-"
                           +(date.getDate()>9?date.getDate():"0"+date.getDate());
                        
                    }

                }
            });
        },
        //编辑
        get_editdata:function(){
            var that = this;
            var options = {};
            options.ID = that.ID;
            options.action = "getqualitycontroldetail";
            ns.post(options, function (succeed, data, err) {
                if (succeed) {
                    that.newform.ProjectID=data.form.ProjectID;
                    that.newform.ProjectName=data.form.fullname;
                    that.newform.CategoryID=data.form.CategoryID;
                    that.newform.CategoryName=data.form.CategoryName;
                    that.newform.InChargeUserID=data.form.InChargeUserIDList[0];
                    that.newform.UserName=data.form.InChargeUserNames;
                    that.newform.CheckUserID=data.form.CheckUserID;
                    that.newform.CheckUserName=data.form.CheckUserName;
                    that.newform.ServiceContent=data.form.ServiceContent;
                    that.getDate(data.form.ServiceEndTime);
                    that.imgEditlist=data.form.imagelist;
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true
            });

        },
        getDate: function (dt) {
            var that=this;
            var myDate = new Date(dt);
            var y = myDate.getFullYear();
            var m = myDate.getMonth() + 1;
            var d = myDate.getDate();
            m = m < 10 ? '0' + m : m;
            var d = d < 10 ? '0' + d : d;
            that.newform.ServiceEndTime=y + '-' + m + '-' + d;
        },
    }
});
apiready = function() {
    api.parseTapmode();
    ns = window.Foresight.Util;
    UIAlbumBrowser = api.require('UIAlbumBrowser');
    app.newform.RelatedID = api.pageParam.RelatedID ||0;
    app.newform.ComeFrom = api.pageParam.ComeFrom ||1;
    app.newform.PlanID = api.pageParam.PlanID ||0;
    app.ID = api.pageParam.ID ||0;
    app.get_data();
    api.addEventListener({
        name: 'do_qualitychoose'
    }, function (ret, err) {
        if (ret) {
            if(ret.value.type==1){
                app.newform.UserName=ret.value.item.FinalRealName;
                app.newform.InChargeUserID=ret.value.item.FinalUserID;
            }
            if(ret.value.type==2){
                app.newform.CheckUserName=ret.value.item.FinalRealName;
                app.newform.CheckUserID=ret.value.item.FinalUserID;
            }
            
        }
    });



};
